<template>
  <div class="address-add">
    <div class="title">
      <svg
        @click="$router.back()"
        t="1671798247143"
        class="icon"
        viewBox="0 0 1024 1024"
        version="1.1"
        xmlns="http://www.w3.org/2000/svg"
        p-id="2281"
        width="200"
        height="200"
      >
        <path
          d="M319.64 512.016l336.016-336.008 45.248 45.248L364.896 557.28z"
          p-id="2282"
        ></path>
        <path
          d="M365.216 466.464l339.976 339.968-45.256 45.256-339.976-339.976z"
          p-id="2283"
        ></path>
      </svg>
      <span v-if="$route.query.type == 'add'">新增收获地址</span>
      <span v-if="$route.query.type == 'edit'">编辑收获地址</span>
      <span></span>
    </div>
    <ul class="list">
      <li>
        <span>联系人</span>
        <input type="text" placeholder="请输入收货人姓名" v-model="username" />
      </li>
      <li>
        <span>联系电话</span>
        <input type="text" placeholder="请输入手机号" v-model="phone" />
      </li>
      <li class="address-check">
        <van-field
          v-model="fieldValue"
          is-link
          readonly
          label="所在地区"
          placeholder="请选择所在地区"
          @click="show = true"
          class="check"
        />
        <van-popup v-model="show" round position="bottom">
          <van-cascader
            v-model="thirdCascaderValue"
            title="请选择所在地区"
            :options="options"
            @close="show = false"
            @finish="onFinish"
            class="ff"
          />
        </van-popup>
      </li>
      <li>
        <span>详细地址</span>
        <input
          type="text"
          placeholder="请输入详细地址，建议5~60字"
          v-model="detailedAddress"
        />
      </li>
    </ul>
    <div class="default">
      <span>设为默认地址</span>
      <van-switch
        v-model="checked"
        active-color="#ee0a24"
        inactive-color="#dcdee0"
        size="24px"
      />
    </div>
    <div class="submit" @click="addAddress">
      {{ $route.query.type == "add" ? "添加" : "保存" }}
    </div>
  </div>
</template>

<script>
import qs from "qs";
import Vue from "vue";
import { Switch, Toast } from "vant";
import { Area } from "vant";
import { Form } from "vant";
import { Field } from "vant";
import { Cascader } from "vant";

Vue.use(Cascader);
Vue.use(Form);
Vue.use(Field);
Vue.use(Area);
Vue.use(Switch);
export default {
  data() {
    return {
      checked: false,
      username: "",
      phone: "",
      address: "",
      detailedAddress: "",
      token: null,
      allAddress: null,
      currentAddress: null,

      show: false,
      fieldValue: "",
      firstCascaderValue: "",
      secondCascaderValue: "",
      thirdCascaderValue: "",

      // 选项列表，children 代表子选项，支持多级嵌套
      options: [],
    };
  },

  async created() {
    this.token = localStorage.getItem("fastCar-token");

    let res = await this.axios({
      url: "https://m-mall.gxptkc.com/v3/system/front/region/list",
      method: "GET",
      headers: {
        authorization: "Bearer " + this.token,
      },
    });
    this.allAddress = res.data.data;

    if (this.$route.query.type == "edit") {
      let currentAddressRes = await this.axios({
        url: `https://m-mall.gxptkc.com/v3/member/front/memberAddress/detail?addressId=${this.$route.query.addressId}`,
        method: "GET",
        headers: {
          authorization: "Bearer " + this.token,
          "content-type": "application/x-www-form-urlencoded",
        },
      });

      this.username = currentAddressRes.data.data.memberName;
      this.phone = currentAddressRes.data.data.telMobile;
      this.checked = currentAddressRes.data.data.isDefault ? true : false;
      this.detailedAddress = currentAddressRes.data.data.detailAddress;
      this.fieldValue = currentAddressRes.data.data.addressAll;
      this.firstCascaderValue = currentAddressRes.data.data.provinceCode;
      this.secondCascaderValue = currentAddressRes.data.data.cityCode;
      this.thirdCascaderValue = currentAddressRes.data.data.districtCode;
    }

    this.options = this.allAddress.map((o) => {
      return {
        text: o.regionName,
        value: o.regionCode,
        regionLevel: o.regionLevel,
        children: o.children.map((item) => {
          return {
            text: item.regionName,
            value: item.regionCode,
            regionLevel: item.regionLevel,
            children: item.children.map((city) => {
              return {
                text: city.regionName,
                value: city.regionCode,
                regionLevel: city.regionLevel,
              };
            }),
          };
        }),
      };
    });
  },

  methods: {
    onFinish({ selectedOptions }) {
      this.firstCascaderValue = selectedOptions[0].value;
      this.secondCascaderValue = selectedOptions[1].value;
      this.show = false;
      this.fieldValue = selectedOptions.map((option) => option.text).join("");
    },
    async addAddress() {
      if (this.detailedAddress.length < 5) {
        Toast("详细地址需要5个字以上！");
        return;
      }
      await this.axios({
        method: "POST",
        url:
          "https://m-mall.gxptkc.com/v3/member/front/memberAddress/" +
          this.$route.query.type,
        headers: {
          authorization: "Bearer " + this.token,
          "content-type": "application/x-www-form-urlencoded",
        },
        data: qs.stringify({
          key: this.token,
          memberName: this.username,
          provinceCode: this.firstCascaderValue,
          cityCode: this.secondCascaderValue,
          districtCode: this.thirdCascaderValue,
          addressAll: this.fieldValue,
          detailAddress: this.detailedAddress,
          telMobile: this.phone,
          isDefault: this.checked ? 1 : 0,
          addressId: this.$route.query.addressId,
        }),
      });

      setTimeout(() => {
        if (this.$route.query.type == "add") {
          Toast("添加成功！");
        } else {
          Toast("保存成功！");
        }

        this.$router.push({
          path: "/address-list",
          query: {
            productId: this.$route.query.productId,
            source: this.$route.query.source,
            cartIds: this.$route.query.cartIds,
          },
        });
      }, 1000);
    },
  },
};
</script>

<style lang="scss">
.address-add {
  background-color: rgb(245, 245, 245);
  height: 100vh;
  width: 100vw;
  > .title {
    display: flex;
    justify-content: space-between;
    padding: 10rem;
    background-color: #fff;
    margin-bottom: 10rem;
    svg {
      width: 25rem;
      height: 25rem;
    }
    span {
      font-size: 16rem;
      color: #000;
      font-weight: bold;
    }
  }
  > ul.list {
    background-color: #fff;
    padding: 0 10rem;
    span {
      display: flex;
      width: 56rem;
    }
    li {
      padding: 15rem;
      border-bottom: 1px solid #eee;
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-size: 14rem;
      color: #333;
      input {
        flex-grow: 1;
        border: none;
        margin-left: 10rem;
      }
      ::-webkit-input-placeholder {
        color: #ccc;
      }
      :-moz-placeholder {
        color: #ccc;
      }
      :-ms-input-placeholder {
        color: #ccc;
      }

      &.address-check {
        display: block;
        padding: 0;
        span {
          color: #333;
          // width: 0;
          margin-right: 0;
        }
        .van-field__label {
          width: 56rem;
          margin-right: 0;
        }
        .van-cell__right-icon {
          font-size: 0;
        }
      }
    }
  }
  > .default {
    margin: 10rem 0;
    padding: 10rem;
    background-color: #fff;
    display: flex;
    justify-content: space-between;
    align-items: center;
    span {
      font-size: 14rem;
      color: #333;
    }
  }
  > .submit {
    margin: 30rem auto;
    width: 80vw;
    height: 40rem;
    color: #fff;
    background-color: #fc1c1c;
    border-radius: 20rem;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 16rem;
  }
}
</style>

